package com.handydata.antifraud.ws;

import com.google.common.base.CaseFormat;
import com.handydata.antifraud.annotation.Comment;
import com.handydata.antifraud.to.WsReqTO;
import com.handydata.antifraud.to.WsResTO;
import org.apache.commons.lang3.tuple.MutablePair;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * ws调用服务抽象类
 * @param <T>
 * @param <R>
 */
public abstract class AbstractWsService<T extends WsReqTO, R extends WsResTO> {

    @Autowired
    private WsServiceFactory wsServiceFactory;
    /**
     * 注册wsService,实现方式调用registerToWsServiceFactory(this, 请求对象.class)
     */
    public abstract void register();

    /**
     * 注册到wsServiceFactory中
     * @param wsService
     * @param reqClass
     */
    @SuppressWarnings("unchecked")
    protected void registerToWsServiceFactory(WsInvocationService<T, R> wsService, Class<?> reqClass) {
        String className = wsService.getClass().getSimpleName();
        String beanName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, className).replace("Impl", "");

        Comment comment = wsService.getClass().getAnnotation(Comment.class);
        if(comment != null) {
            beanName = beanName + ":" + comment.value();
        }

        MutablePair<WsInvocationService<WsReqTO, WsResTO>, Class<?>> pair = new MutablePair<>((WsInvocationService<WsReqTO, WsResTO>)wsService, reqClass);
        wsServiceFactory.registerWsService(beanName, pair);
    };
}
